﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using com.dz.ht.components;
using com.dz.ht.common;
using System.Text.RegularExpressions;
using System.Web;
namespace com.dz.ht.ui
{
    public partial class FrmBookSearchSite : Form
    {
        string m_site_url = string.Empty;
        string m_book_id = string.Empty;
        string m_book_name = string.Empty;
        string m_str_sql = string.Empty;
        StringBuilder m_sb = new StringBuilder();
        public FrmBookSearchSite()
        {
            InitializeComponent();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            m_sb = new StringBuilder();
            m_sb.Append(" where 1=1 ");
            if (cmbSiteUrl.Text == "有")
            {
                m_sb.Append(" and exists(select 1 from tbbookSearch b where a.bookId=b.bookId) ");
          
            }
            else if (cmbSiteUrl.Text == "无")
            {
              
                m_sb.Append(" and not exists(select 1 from tbbookSearch b where a.bookId=b.bookId) ");
            }

            if (!string.IsNullOrEmpty(txtBookId.Text.Trim()))
            {
                m_sb.Append(string.Format(" and bookId={0} ", txtBookId.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtBookName.Text.Trim()))
            {
                m_sb.Append(string.Format(" and bookName like '%{0}%' ", txtBookName.Text.Trim()));
            }

            m_str_sql = "select bookId,bookName,wordscount,collect,lastupdatetime from tbbook a " + m_sb.ToString();
            try
            {
                DataManger db = new DataManger();
                DataSet ds = db.QueryData(m_str_sql);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    dgvData.DataSource = ds.Tables[0];
                   
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("绑定小说列表失败" + ex.ToString());
            }
        }

        private void FrmBookSearchSite_Load(object sender, EventArgs e)
        {
            BindData();
        }

        private void 查询最新更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvData.SelectedRows.Count <= 0)
                return;

            string t_book_id = dgvData.SelectedRows[0].Cells[0].Value.ToString();
            string t_book_name = dgvData.SelectedRows[0].Cells[1].Value.ToString();
            FrmUpdateSitiList t_frm = new FrmUpdateSitiList(t_book_id, t_book_name);
            t_frm.ShowDialog();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string t_sql_sql = "select bookId,bookName,wordscount,collect,lastupdatetime from tbbook a where not exists(select 1 from tbbookSearch b where a.bookId=b.bookId)";
            long t_book_id=0;
            try
            {
                DataManger db = new DataManger();
                DataSet ds = db.QueryData(t_sql_sql);

                t_sql_sql = "select siteDomain from tbbooksite";

                DataSet dsSite = db.QueryData(t_sql_sql);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                    {
                        if(!long.TryParse(ds.Tables[0].Rows[index]["bookId"].ToString(),out t_book_id))
                            t_book_id=0;
                        UpdateDb(t_book_id, ds.Tables[0].Rows[index]["bookName"].ToString(), dsSite);
                    }

                    MessageBox.Show("已经完成！");

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("绑定小说列表失败" + ex.ToString());
            }
        }

        private void UpdateDb(long i_book_id,string i_book_name,DataSet ds)
        {
            DataManger db = new DataManger();
            bool t_is_updated = false;
            /// <summary>
            /// 百度首页编码
            /// </summary>
            Encoding t_encoding = Encoding.GetEncoding("gb2312");
            string i_chapter_content_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(string.Format("{0} 最新章节", i_book_name), t_encoding));

            string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, t_encoding);

            if (!string.IsNullOrEmpty(t_html))
            {
                MatchCollection t_ma = Regex.Matches(t_html, "<h3\\s*?class=[\'\"]?t[\'\"]?><a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h3>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_ma == null || t_ma.Count <= 0)
                    return;

                SearchSiteInfo t_site_info = new SearchSiteInfo();

                foreach (Match t_mc in t_ma)
                {
                    for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                    {
                        if (t_mc.Groups[1].Value.ToString().Contains(ds.Tables[0].Rows[index]["siteDomain"].ToString()))
                        {
                            t_site_info.SiteDomain = ds.Tables[0].Rows[index]["siteDomain"].ToString();
                            t_site_info.ChapterUrl = t_mc.Groups[1].Value.ToString();
                            t_site_info.BookId = i_book_id;
                            db.UpdateBookSearchSite(t_site_info);
                            t_is_updated = true;
                            break;
                        }
                    }
                    if (t_is_updated)
                        break;
                }

                
            }
        }

        private void 指定章节地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvData.SelectedRows.Count <= 0)
                return;

            string t_book_id = dgvData.SelectedRows[0].Cells[0].Value.ToString();
            string t_book_name = dgvData.SelectedRows[0].Cells[1].Value.ToString();
            FrmChapterUrl t_frm = new FrmChapterUrl();
            DialogResult dlr = t_frm.ShowDialog();

            if (dlr == DialogResult.OK)
            {
                if (t_frm.ActionType == 0)
                {
                    FrmRegChapterList t_chapter = new FrmRegChapterList(t_book_id, t_book_name, t_frm.ChapterUrl);
                    t_chapter.ShowDialog();
                }
                else
                {


                    Uri t_domain_url = new Uri(t_frm.ChapterUrl);

                    SearchSiteInfo t_site = new SearchSiteInfo();
                    long l_book_id = 0;
                    if (!long.TryParse(t_book_id, out l_book_id))
                        l_book_id = 0;
                    t_site.BookId = l_book_id;
                    t_site.ChapterUrl = t_frm.ChapterUrl;
                    t_site.SiteDomain = "http://" + t_domain_url.Host;

                    try
                    {
                        DataManger db = new DataManger();
                        int ret = db.UpdateBookSearchSite(t_site);
                        if (ret == Consts.Success)
                        {
                            MessageBox.Show("保存成功");
                        }
                        else
                        {
                            MessageBox.Show("库存没有");
                        }

                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("保存搜索站点失败" + ex.ToString());
                        MessageBox.Show("保存失败");
                    }
                }
            }
        }
    }
}
